<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Utils\Enum\RedisEnum;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use RedisException;

abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    protected LoggerInterface $logger;

    public function __construct()
    {
        try {
            $this->logger = $this->container->get(LoggerFactory::class)->get('api', 'api');
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
        }
    }

    /**
     * API返回.
     */
    protected function apiReturn(int $code = 200, string $msg = 'succ', array $data = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    /**
     * 解析token.
     */
    protected function parseToken(): void
    {
        $token = $this->request->header('token');
        if (! empty($token)) {
            try {
                $redis = $this->container->get(Redis::class);
                $userinfo = $redis->hGetAll(RedisEnum::PREFIX_TOKEN . $token);
                if ($userinfo) {
                    foreach ($userinfo as $k => $v) {
                        if ($k == 'userid' || $k == 'roleId') {
                            $v = (int)$v;
                        }
                        Context::set($k, $v);
                    }
                }
            } catch (ContainerExceptionInterface|NotFoundExceptionInterface|RedisException $e) {
            }
        }
    }
}
